import 'package:flutter/material.dart';
import 'level_manager.dart';
import 'level_models.dart';
import 'math_brick_game.dart'; // 导入游戏组件

// 定义UI常量
const double _kIconSize = 48.0;
const double _kTextFontSize = 20.0;
const double _kSubtextFontSize = 16.0;
const double _kIconSpacing = 4.0;
const double _kCardElevation = 3.0;
const double _kBorderRadius = 16.0;
const EdgeInsets _kPadding = EdgeInsets.all(16.0);
const double _kVerticalSpacing = 16.0;

/// 关卡状态展示组件
class LevelStatusIndicator extends StatelessWidget {
  final LevelStatus status;
  
  const LevelStatusIndicator({super.key, required this.status});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          _getIconDataForStatus(status),
          size: _kIconSize * 0.5,
          color: _getColorForStatus(status),
        ),
        const SizedBox(width: _kIconSpacing),
        Text(
          status.chineseName,
          style: TextStyle(color: _getColorForStatus(status)),
        ),
      ],
    );
  }

  /// 根据关卡状态获取对应的图标
  IconData _getIconDataForStatus(LevelStatus status) {
    switch (status) {
      case LevelStatus.locked:
        return Icons.lock;
      case LevelStatus.unlocked:
        return Icons.lock_open;
      case LevelStatus.completed:
        return Icons.check_circle;
    }
  }

  /// 根据关卡状态获取对应的颜色
  Color _getColorForStatus(LevelStatus status) {
    switch (status) {
      case LevelStatus.locked:
        return Colors.grey;
      case LevelStatus.unlocked:
        return Colors.blue;
      case LevelStatus.completed:
        return Colors.green;
    }
  }
}

/// 单个关卡卡片组件
class LevelCard extends StatelessWidget {
  final LevelCategory category;
  final DifficultyTier difficulty;
  final Future<LevelStatus> statusFuture;
  final String levelId;
  final VoidCallback? onTap;

  const LevelCard({
    super.key,
    required this.category,
    required this.difficulty,
    required this.statusFuture,
    required this.levelId,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: _kCardElevation,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(_kBorderRadius),
      ),
      child: FutureBuilder<LevelStatus>(
        future: statusFuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          
          final status = snapshot.data!;
          final isLocked = status == LevelStatus.locked;
          
          return InkWell(
            onTap: isLocked ? null : onTap,
            child: Padding(
              padding: _kPadding,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Icon(
                    category.icon,
                    size: _kIconSize,
                    color: _getColorForStatus(status),
                  ),
                  const SizedBox(height: _kVerticalSpacing),
                  Text(
                    category.name,
                    style: TextStyle(fontSize: _kTextFontSize),
                    textAlign: TextAlign.center,
                  ),
                  Text(
                    '难度: ${difficulty.name}',
                    style: TextStyle(fontSize: _kSubtextFontSize),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 8),
                  LevelStatusIndicator(status: status),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /// 根据关卡状态获取对应的颜色
  Color _getColorForStatus(LevelStatus status) {
    switch (status) {
      case LevelStatus.locked:
        return Colors.grey;
      case LevelStatus.unlocked:
        return Colors.blue;
      case LevelStatus.completed:
        return Colors.green;
    }
  }
}

/// 关卡选择屏幕 - 展示所有可玩的关卡卡片
class LevelSelectionScreen extends StatelessWidget {
  final LevelManager levelManager;

  const LevelSelectionScreen({super.key, required this.levelManager});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('选择关卡')),
      body: Padding(
        padding: _kPadding,
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: _kVerticalSpacing,
            crossAxisSpacing: _kVerticalSpacing,
          ),
          itemCount: levelManager.categories.length * levelManager.difficultyLevels.length,
          itemBuilder: (context, index) {
            // 根据索引确定关卡类别和难度等级
            final categoryIndex = index ~/ levelManager.difficultyLevels.length;
            final difficultyIndex = index % levelManager.difficultyLevels.length;
            final category = levelManager.categories[categoryIndex];
            final difficulty = levelManager.difficultyLevels[difficultyIndex];
            
            // 生成关卡ID（如：加法1）
            final levelId = '${category.name}${difficulty.level}';
            
            // 获取关卡状态
            final statusFuture = levelManager.getStatus(levelId);
            
            return LevelCard(
              category: category,
              difficulty: difficulty,
              statusFuture: statusFuture,
              levelId: levelId,
              onTap: () => _navigateToGame(context, levelId),
            );
          },
        ),
      ),
    );
  }
  
  /// 导航到游戏页面
  void _navigateToGame(BuildContext context, String levelId) {
    print("_navigateToGame, Navigating to game with levelId: $levelId");
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MathBrickGame(selectedLevelId: levelId),
      ),
    );
  }
}
